package com.ujs.edu.medicine.util;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.UploadManager;



public class QiNiuFileUpUtil {

    private static String accessKey = "lJPTF8xKdw7C6VyerKfCQhEj8RPhL13zzL8to4vR";
    private static String secretKey = "PIVezNsDuD9bI0WfwzpsM66NJJ8mOxEXxSg5FXEJ";
    private static String bucket = "cloud-medicine";
    private static String domian = "cloud-medicine.youchen-blog.cn";

    public static String upload(byte[] uploadBytes, String key) {
        StringBuffer fileUrl=new StringBuffer(domian);
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            // 调用put方法上传
            Response res = uploadManager.put(uploadBytes, key, upToken);
            // 打印返回的信息
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
           fileUrl.append("/"+key);
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException qe) {
                // ignore
            }
        }
        return fileUrl.toString();
    }

}

